package com.xiaohei.crm.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaohei.crm.common.exception.XiaoheiException;
import com.xiaohei.crm.common.result.Result;
import com.xiaohei.crm.dao.Role;
import com.xiaohei.crm.dao.User;
import com.xiaohei.crm.mapper.RoleMapper;
import com.xiaohei.crm.mapper.UserMapper;
import com.xiaohei.crm.service.RoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

import static com.xiaohei.crm.common.RedisEnums.ROLE_REGISTRY_KEY;
import static com.xiaohei.crm.common.result.ResultCodeEnum.*;

/**
 * ClassName: RoleServiceImpl
 * Package:
 * Description:
 *
 * @Author:xiaohei
 * @Create 2024/6/22 14:32
 * Version 1.0
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<IPage> findByPage() {
        Page<Role> page = new Page<>();
        LambdaQueryWrapper<Role> eq = Wrappers.lambdaQuery(Role.class).eq(Role::getDelFlag, 0);
        return Result.ok(roleMapper.selectPage(page, eq));
    }

    @Override
    public void saveRole(Role role) {
        String s = stringRedisTemplate.opsForValue().get(ROLE_REGISTRY_KEY + role.getId());
        if (s != null) {
            throw new XiaoheiException(ROLE_IS_AlREADY);
        }

        int isInsert = baseMapper.insert(role);
        if (isInsert < 1) {
            throw new XiaoheiException(DATA_ERROR);
        }

        stringRedisTemplate.opsForValue()
                .set(ROLE_REGISTRY_KEY + role.getId(),role.getId() + role.getRoleName());

    }

    @Override
    public void updateByRoleId(Role role) {
        String s = stringRedisTemplate.opsForValue().get(ROLE_REGISTRY_KEY + role.getId());
        if (s == null) {
            throw new XiaoheiException(DATA_ERROR);
        }

        LambdaQueryWrapper<Role> eq = Wrappers.lambdaQuery(Role.class).eq(Role::getId, role.getId());
        int update = baseMapper.update(role, eq);

        if(update < 1) {
            throw new XiaoheiException(DATA_ERROR);
        }

    }

    @Override
    public void deleteById(String id) {
        String s = stringRedisTemplate.opsForValue().get(ROLE_REGISTRY_KEY + id);
        if (s == null) {
            throw new XiaoheiException(DATA_ERROR);
        }

        LambdaQueryWrapper<User> userRoleQueryWrapper =
                Wrappers.lambdaQuery(User.class)
                        .eq(User::getDelFlag, 0);
        List<User> userList = userMapper.selectList(userRoleQueryWrapper);
        //过滤之后包含对应角色id的集合
        List<User> collect = userList.stream()
                .filter(user -> user.getRole().equals(id))
                .collect(Collectors.toList());

        if(!CollectionUtil.isEmpty(collect)) {
            throw new XiaoheiException(ROLE_HAS_USER_ALREADY_USE);
        }

        //没有使用该角色的用户了才可以删除
        LambdaUpdateWrapper<Role> updateWrapper =
                Wrappers.lambdaUpdate(Role.class).eq(Role::getId, id);
        Role role = Role.builder().delFlag(1).build();
        int update = baseMapper.update(role, updateWrapper);
        if(update<1) {
            throw new XiaoheiException(DATA_ERROR);
        }

        stringRedisTemplate.delete(ROLE_REGISTRY_KEY + id);
    }
}
